﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;

namespace AccelerateSensor.Model.Gateway
{
    public class GatewayPrivateAttributeInfo
    {
        public int StartFreq { get; set; }
        public int AntennaGain { get; set; }
        public int RfChNum { get; set; }
        public string ChannelDataRate { get; set; }

        public List<Dictionary<string, bool>> SfList
        {
            get
            {
                var sfList = new List<Dictionary<string, bool>>();
                
                var jArray = JArray.Parse(ChannelDataRate);
                if (jArray != null)
                {
                    foreach (var token in jArray)
                    {
                        var jObject = token.ToObject<JObject>();

                        var sfDic = new Dictionary<string, bool>();
                        for (var i = 7; i < 12; i++)
                        {
                            var propertyName = $"SF{i}";
                            JToken sfToken;
                            jObject.TryGetValue(propertyName, out sfToken);
                            var sf = sfToken?.ToObject<bool>() ?? false;
                            sfDic.Add(propertyName, sf);
                        }

                        sfList.Add(sfDic);
                    }
                }

                return sfList;
            }
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            foreach (var sfDict in SfList)
            {
                sb.AppendLine("{");
                foreach (var item in sfDict)
                {
                    sb.AppendLine($"{item.Key}: {item.Value}");
                }

                sb.AppendLine("}");
            }
            return $"GatewayPrivateAttributeInfo:{Environment.NewLine}" +
                   $"StartFreq: {StartFreq}, AntennaGain: {AntennaGain}, RfChNum: {RfChNum}, " +
                   $"SfList: {Environment.NewLine}{sb}.";
        }
    }
}
